<template>
  <div class="employee-container">
    <!-- 搜索区域 -->
    <div v-auth-dir="`sys:user:list`" class="search-container">
      <div class="search-label">员工姓名：</div>
      <el-input v-model="data.name" clearable placeholder="请输入内容" class="search-main" />
      <el-button type="primary" @click="searchEmployee">查询</el-button>
    </div>
    <div class="create-container">
      <el-button v-auth-dir="`sys:user:add_edit`" type="primary" @click="openDialog(0)">添加员工</el-button>
    </div>
    <!-- 表格区域 -->
    <div class="table">
      <el-table style="width: 100%" :data="employeeList">
        <el-table-column type="index" label="序号" />
        <el-table-column label="员工姓名" width="180" prop="name" />
        <el-table-column label="登录账号" width="180" prop="userName" />
        <el-table-column label="联系方式" width="120" prop="phonenumber" />
        <el-table-column label="角色" width="120" prop="roleName" />
        <el-table-column label="状态">
          <template #default="scope">
            {{ scope.row.status ? '启用':'禁用' }}
          </template>
        </el-table-column>
        <el-table-column label="添加时间" prop="createTime" />
        <el-table-column label="操作" fixed="right" width="120">
          <template #default="scope">
            <el-button
              v-auth-dir="`sys:user:add_edit`"
              size="mini"
              type="text"
              @click="openDialog(scope.row.id)"
            >编辑</el-button>
            <el-button
              v-auth-dir="`sys:user:remove`"
              size="mini"
              type="text"
              @click="delEmployee(scope.row.id)"
            >删除</el-button>
            <el-button
              v-auth-dir="`sys:user:resetPwd`"
              size="mini"
              type="text"
              @click="resetPwd(scope.row.id)"
            >重置密码</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="page-container">
      <el-pagination
        background
        layout="prev, pager, next"
        :page-size="params.pageSize"
        :total="total"
        @current-change="pageChangeFn"
      />
    </div>
    <!-- 添加员工 -->
    <el-dialog
      :visible.sync="dialogVisible"
      :title="title"
      width="480px"
    >
      <!-- 表单接口 -->
      <div class="form-container">
        <el-form ref="addForm" :model="addForm" :rules="addFormRules" label-width="80px">
          <el-form-item label="员工姓名" prop="name">
            <el-input v-model="addForm.name" />
          </el-form-item>
          <el-form-item label="登录账号" prop="userName">
            <el-input v-model="addForm.userName" />
          </el-form-item>
          <el-form-item label="联系方式" prop="phonenumber">
            <el-input v-model="addForm.phonenumber" />
          </el-form-item>
          <el-form-item label="分配角色" prop="roleId">
            <el-select v-model="addForm.roleId" placeholder="请选择角色">
              <el-option
                v-for="item in roleList"
                :key="item.roleId"
                :label="item.roleName"
                :value="item.roleId"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="员工状态" prop="status">
            <el-radio-group v-model="addForm.status">
              <el-radio :label="0">禁用</el-radio>
              <el-radio :label="1">启用</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <el-button size="mini" @click="closeDialog">取 消</el-button>
        <el-button size="mini" type="primary" @click="createEmployee">确 定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { getEmployeeListAPI, createEmployeeAPI, delEmployeeAPI, resetPwdAPI, searchEmployeeAPI } from '@/apis/employee'
import { getRoleListAPI } from '@/apis/role'
export default {
  name: 'Employee',
  data() {
    return {
      params: {
        page: 1, // 页码
        pageSize: 2 // 条数
      },
      total: 0, // 总共条数
      employeeList: [], // 员工列表
      dialogVisible: false, // 弹窗控制
      addForm: {
        name: '',
        phonenumber: '',
        roleId: '',
        roleName: '',
        status: 1,
        userName: ''
      },
      addFormRules: {
        name: [
          { required: true, message: '请输入员工姓名', trigger: 'blur' }
        ],
        userName: [
          { required: true, message: '请输入登录账号', trigger: 'blur' }
        ],
        phonenumber: [
          { required: true, message: '请输入联系方式', trigger: 'blur' }
        ],
        roleId: [
          { required: true, message: '请分配角色', trigger: 'blur' }
        ],
        status: [
          { required: true, message: '请选择员工状态', trigger: 'blur' }
        ]
      },
      roleList: [], // 角色列表
      type: '',
      data: {
        name: '' // 员工姓名
      }
    }
  },
  computed: {
    title() {
      if (this.type) {
        return '编辑员工'
      } else {
        return '添加员工'
      }
    }
  },
  created() {
    this.getEmployeeList()
    // 页面创建时获取角色列表-否则点击添加，编辑需要请求多次
    this.getRoleList()
  },
  methods: {
    // 获取员工列表
    async getEmployeeList() {
      const res = await getEmployeeListAPI(this.params)
      // console.log(res)
      this.employeeList = res.data.rows
      this.total = res.data.total
    },
    // 切换分页
    pageChangeFn(nextPage) {
      // console.log(a,b,c)
      this.params.page = nextPage
      this.getEmployeeList()
    },
    // 关闭弹窗
    closeDialog() {
      this.dialogVisible = false
      this.$refs.addForm.resetFields()
    },
    openDialog(id) {
      if (id) {
        this.type = '编辑员工'
        this.dialogVisible = true
        this.employeeList.forEach(item => {
          if (item.id === id) {
            for (const key in this.addForm) { this.addForm[key] = item[key] }
          }
        })
      } else {
        this.type = ''
        this.dialogVisible = true
        // 点击添加新用户时，清空编辑员工回显的数据
        this.$refs.addForm.resetFields()
      }
    },
    // 获取角色列表
    async getRoleList() {
      const res = await getRoleListAPI()
      console.log(res)
      this.roleList = res.data
    },
    // 创建新用户
    async createEmployee() {
      await this.$refs.addForm.validate()
      this.roleList.forEach(item => {
        if (item.roleId === this.addForm.roleId) {
          this.addForm.roleName = item.roleName
        }
      })
      // console.log(this.addForm)
      const res = await createEmployeeAPI({
        ...this.addForm
      })
      // console.log(res.msg)
      this.$message({
        type: 'success',
        message: `${res.msg}`
      })
      this.dialogVisible = false
      this.$refs.addForm.resetFields()
      this.getEmployeeList()
    },
    // 删除指定用户信息
    delEmployee(id) {
      this.$confirm('删除员工后将不可登录，确定要删除吗', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        await delEmployeeAPI(id)
        this.$message({
          type: 'success',
          message: '删除成功'
        })
        this.getEmployeeList()
        console.log('这里执行了没')
      })
      // const res = await delEmployeeAPI(id)
      // console.log(res)
    },
    // 重置密码
    async resetPwd(id) {
      this.$confirm('确定要将此账户密码重置为：123456 吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }).then(async() => {
        // eslint-disable-next-line no-sequences
        await resetPwdAPI({ id }),
        this.$message({
          type: 'success',
          message: '重置成功'
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消操作'
        })
      })
    },
    async searchEmployee() {
      if (!this.data.name) {
        this.$message({
          type: 'warning',
          message: '查找员工姓名不能为空'
        })
        return
      }

      const res = await searchEmployeeAPI(this.data)
      // console.log(res)

      // this.employeeList.forEach(item => {
      //   for (const keys in res.data.rows) {
      //     this.employeeList[keys] = res.data.rows[keys]
      //   }
      // })
      // this.employeeList = []
      this.total = res.data.total
      this.employeeList = res.data.rows
      // res.data.rows.forEach(item => {
      //   for (const key in this.employeeList) {
      //     this.employeeList[key] = item[key]
      //   }
      // })
    }
  }
}
</script>

<style lang="scss" scoped>
.employee-container {
  padding: 10px;
}

.search-container {
  display: flex;
  align-items: center;
  border-bottom: 1px solid rgb(237, 237, 237, .9);
  ;
  padding-bottom: 20px;

  .search-label {
    width: 100px;
  }

  .search-main {
    width: 220px;
    margin-right: 10px;
  }
}
.create-container{
  margin: 10px 0px;
}
.page-container{
  padding:4px 0px;
  text-align: right;
}
.form-container{
  padding:0px 80px;
}
</style>
